<template>
	<view class="login-container">
		<!-- 顶部装饰波浪 -->
		<view class="wave-decoration"></view>
		
		<!-- 主要内容区 -->
		<view class="content-wrapper">
			<!-- Logo区域 -->
			<view class="logo-section">
				<image class="logo" :src="systemConfig.logoUrl" mode="aspectFit"></image>
				<view class="brand">
					<text class="title">印爪云宠</text>
					<text class="subtitle">您的专属宠物管家</text>
				</view>
				<!-- 装饰性爪印 -->
				<view class="paw-prints">
					<view class="paw paw-1"></view>
					<view class="paw paw-2"></view>
					<view class="paw paw-3"></view>
				</view>
			</view>

			<!-- 登录按钮区域 -->
			<view class="login-section">
				<button 
					class="login-button" 
					:loading="isLoading"
					:disabled="isLoading"
					open-type="getUserInfo"
					@tap="handleLogin"
					@getuserinfo="onGetUserInfo">
					<u-icon name="weixin-fill" color="#FFFFFF" size="40"></u-icon>
					<text>{{ isLoading ? '登录中...' : '微信一键登录' }}</text>
				</button>

				<!-- 协议提示 -->
				<view class="agreement-tips">
					<text class="tips-text">登录即代表您已阅读并同意</text>
					<view class="links">
						<navigator url="/pages/agreement/privacy" class="link">《隐私政策》</navigator>
						<text class="separator">和</text>
						<navigator url="/pages/agreement/service" class="link">《用户协议》</navigator>
					</view>
				</view>

				
			</view>
		</view>

		<!-- 底部装饰 -->
		<view class="bottom-decoration">
			<view class="paw-trail"></view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			isLoading: false,
			errorMsg: '',
			userInfo: null,
			systemConfig: {
				logoUrl: '',
				loginBgUrl: '',
				appName: '',
				appDesc: ''
			}
		}
	},
	onLoad() {
		// 检查是否已登录
		this.checkLoginStatus();
		// 加载系统配置
		this.loadSystemConfig();
	},
	methods: {
		// 加载系统配置
		async loadSystemConfig() {
			try {
				// 查询全局配置
				const result = await this.$leanCloud.query('SystemConfig', {
					global: true
				});
				
				if (result && result.results && result.results.length > 0) {
					// 使用第一条配置记录
					this.systemConfig = {
						...this.systemConfig,
						...result.results[0]
					};
				}
			} catch (error) {
				console.error('加载系统配置失败:', error);
			}
		},
		// 检查登录状态
		async checkLoginStatus() {
			try {
				const user = await this.$leanCloud.user.getCurrent();
				if (user) {
					// 已登录，直接跳转到主页
					// this.navigateToIndex();
				}
			} catch (error) {
				console.error('检查登录状态失败:', error);
			}
		},
		
		// 获取用户信息回调
		onGetUserInfo(e) {
			console.log('获取用户信息回调:', e);
			if (e.detail.userInfo) {
				// 保存用户信息到全局数据
				if (getApp() && getApp().globalData) {
					Object.assign(getApp().globalData, {
						nickname: e.detail.userInfo.nickName,
						avatarUrl: e.detail.userInfo.avatarUrl
					});
				}
				
				// 保存用户信息
				this.userInfo = e.detail.userInfo;
			}
		},
		
		// 登录按钮点击事件
		handleLogin() {
			if (this.isLoading) return;
			
			this.isLoading = true;
			this.errorMsg = '';
			
			// 显示加载提示
			wx.showLoading({
				title: '登录中...'
			});
			console.log('微信登录');
			// 调用微信登录获取code
			wx.login({
				success: (res) => {
					if (res.code) {
						console.log('获取微信code成功:', res.code);
						this.doLogin();
					} else {
						console.error('获取微信code失败:', res);
						this.showError('登录失败，请重试');
					}
				},
				fail: (err) => {
					console.error('微信登录接口调用失败:', err);
					this.showError('网络异常，请检查连接');
				}
			});
		},
		
		// 显示错误信息
		showError(message) {
			wx.hideLoading();
			this.errorMsg = message;
			this.isLoading = false;
			wx.showToast({
				title: message,
				icon: 'none'
			});
		},
		
		// 执行登录
		async doLogin() {
			try {
				console.log('开始调用LeanCloud微信登录');
				// 确保获取最新的微信code
				const loginResult = await new Promise((resolve, reject) => {
					wx.login({
						success: (res) => {
							if (res.code) {
								console.log('doLogin内重新获取微信code成功:', res.code);
								resolve(res);
							} else {
								console.error('doLogin内获取微信code失败:', res);
								reject(new Error('微信登录code获取失败'));
							}
						},
						fail: (err) => {
							console.error('doLogin内微信登录API调用失败:', err);
							reject(err);
						}
					});
				});
				
				// 调用微信登录
				console.log('尝试调用LeanCloud wechatLogin方法');
				const result = await this.$leanCloud.user.wechatLogin();
				console.log('微信登录成功:', result);
				
				// 额外检查登录结果
				if (!result) {
					console.error('微信登录结果为空');
					throw new Error('登录失败，请重试');
				}
				
				// 检查用户token
				const sessionToken = wx.getStorageSync('leancloud_session_token');
				const userId = wx.getStorageSync('leancloud_user_id');
				console.log('登录后存储信息:', { sessionToken: !!sessionToken, userId });
				
				if (!sessionToken) {
					console.error('登录成功但未获取到会话令牌');
					throw new Error('会话令牌获取失败');
				}
				
				// 获取微信用户信息 - 只在首次登录时更新
				try {
					// 检查是否是首次登录
					const currentUser = await this.$leanCloud.user.getCurrent();
					const isFirstLogin = !currentUser.get('nickname') && !currentUser.get('avatarUrl');
					
					if (isFirstLogin) {
						console.log('首次登录，更新用户信息');
						// 如果从按钮回调已经获取到了用户信息
						if (this.userInfo) {
							console.log('使用已经获取的用户信息:', this.userInfo);
							// 更新用户头像和昵称到LeanCloud
							await this.$leanCloud.user.updateUserInfo(this.userInfo);
						} else {
							// 使用微信提供的API获取用户信息
							const userInfoRes = await new Promise((resolve, reject) => {
								wx.getUserInfo({
									success: res => {
										console.log('获取微信用户信息成功:', res);
										resolve(res);
									},
									fail: err => {
										console.error('获取微信用户信息失败:', err);
										resolve(null);
									}
								});
							});
							
							// 如果成功获取用户信息，更新到LeanCloud用户资料
							if (userInfoRes && userInfoRes.userInfo) {
								console.log('更新用户资料:', userInfoRes.userInfo);
								// 更新用户头像和昵称到LeanCloud
								await this.$leanCloud.user.updateUserInfo(userInfoRes.userInfo);
								
								// 将用户信息保存到全局数据
								if (getApp() && getApp().globalData) {
									Object.assign(getApp().globalData, {
										nickname: userInfoRes.userInfo.nickName,
										avatarUrl: userInfoRes.userInfo.avatarUrl,
										isLogin: true
									});
								}
							}
						}
					} else {
						console.log('非首次登录，保持现有用户信息');
						// 更新全局数据
						if (getApp() && getApp().globalData) {
							Object.assign(getApp().globalData, {
								nickname: currentUser.get('nickname'),
								avatarUrl: currentUser.get('avatarUrl'),
								isLogin: true
							});
						}
					}
				} catch (userInfoError) {
					console.error('处理用户信息过程中出错:', userInfoError);
					// 这里不抛出错误，因为即使更新用户信息失败，登录流程也应该继续
				}
				
				// 登录成功，跳转到首页
				wx.hideLoading();
				console.log('登录成功，即将跳转到首页');
				this.navigateToIndex();
			} catch (error) {
				console.error('微信登录过程中出错:', error);
				this.showError('登录失败: ' + (error.message || '请重试'));
			} finally {
				this.isLoading = false;
			}
		},
		
		// 跳转到首页
		navigateToIndex() {
			wx.switchTab({
				url: '/pages/index/index'
			});
		},
		
		// 跳转到系统配置页面
		navigateToConfig() {
			uni.navigateTo({
				url: '/pages/admin/systemConfig'
			});
		}
	}
}
</script>

<style lang="scss">
page {
	background: linear-gradient(to bottom, #F5F6FA, #FFFFFF);
}

.login-container {
	min-height: 100vh;
	position: relative;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

/* 波浪装饰 */
.wave-decoration {
	height: 400rpx;
	background: linear-gradient(45deg, #8B5CFF, #A47EFF);
	position: relative;
	overflow: hidden;

	&::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 120rpx;
		background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="%23ffffff" fill-opacity="1" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,112C672,96,768,96,864,112C960,128,1056,160,1152,160C1248,160,1344,128,1392,112L1440,96L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>');
		background-size: cover;
		transform: translateY(2px);
	}
}

/* 主要内容区 */
.content-wrapper {
	flex: 1;
	padding: 0 60rpx;
	position: relative;
	z-index: 1;
	margin-top: -160rpx;
}

/* Logo区域 */
.logo-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;

	.logo {
		width: 180rpx;
		height: 180rpx;
		border-radius: 20rpx;
		box-shadow: 0 20rpx 40rpx rgba(139, 92, 255, 0.15);
		background: transparent;
		padding: 0;
		object-fit: contain;
	}

	.brand {
		margin-top: 30rpx;
		text-align: center;

		.title {
			font-size: 48rpx;
			font-weight: bold;
			color: #333333;
			display: block;
			margin-bottom: 10rpx;
		}

		.subtitle {
			font-size: 28rpx;
			color: #666666;
			display: block;
		}
	}
}

/* 装饰性爪印 */
.paw-prints {
	position: absolute;
	width: 100%;
	height: 100%;
	pointer-events: none;

	.paw {
		position: absolute;
		width: 40rpx;
		height: 40rpx;
		background: rgba(139, 92, 255, 0.1);
		border-radius: 50%;

		&::before, &::after {
			content: '';
			position: absolute;
			width: 20rpx;
			height: 20rpx;
			background: rgba(139, 92, 255, 0.1);
			border-radius: 50%;
		}

		&::before {
			top: -15rpx;
			left: -5rpx;
		}

		&::after {
			top: -15rpx;
			right: -5rpx;
		}

		&.paw-1 {
			top: 40%;
			left: 15%;
			transform: rotate(-30deg);
		}

		&.paw-2 {
			top: 30%;
			right: 20%;
			transform: rotate(45deg);
		}

		&.paw-3 {
			bottom: 20%;
			left: 25%;
			transform: rotate(-15deg);
		}
	}
}

/* 登录按钮区域 */
.login-section {
	margin-top: 100rpx;
	padding: 0 30rpx;

	.login-button {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100rpx;
		background: linear-gradient(to right, #8B5CFF, #A47EFF);
		border-radius: 50rpx;
		box-shadow: 0 20rpx 40rpx rgba(139, 92, 255, 0.3);
		border: none;
		margin-bottom: 40rpx;

		&::after {
			border: none;
		}

		text {
			color: #FFFFFF;
			font-size: 32rpx;
			margin-left: 20rpx;
		}

		&:active {
			transform: translateY(2rpx);
			box-shadow: 0 10rpx 20rpx rgba(139, 92, 255, 0.2);
		}
	}
}

/* 协议提示 */
.agreement-tips {
	text-align: center;
	padding: 20rpx 0;

	.tips-text {
		font-size: 24rpx;
		color: #999999;
		margin-bottom: 10rpx;
		display: block;
	}

	.links {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 10rpx;

		.link {
			color: #8B5CFF;
			font-size: 24rpx;
		}

		.separator {
			color: #999999;
			font-size: 24rpx;
		}
	}
}

/* 系统配置入口 */
.config-entry {
	position: fixed;
	right: 30rpx;
	bottom: 30rpx;
	background: rgba(255, 255, 255, 0.9);
	border-radius: 40rpx;
	padding: 16rpx 30rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	backdrop-filter: blur(10px);
	
	text {
		margin-left: 10rpx;
		font-size: 28rpx;
		color: #8B5CFF;
	}
	
	&:active {
		opacity: 0.8;
	}
}

/* 底部装饰 */
.bottom-decoration {
	position: absolute;
	bottom: 0;
	left: 0;
	width: 100%;
	height: 120rpx;
	overflow: hidden;

	.paw-trail {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60"><g fill="%238B5CFF" fill-opacity="0.1"><circle cx="30" cy="30" r="6"/><circle cx="22" cy="25" r="4"/><circle cx="38" cy="25" r="4"/></g></svg>');
		background-repeat: repeat-x;
		background-size: 60rpx;
		opacity: 0.5;
	}
}
</style> 